package org.artifact.core.server;

import cn.hutool.core.getter.OptNullBasicTypeFromObjectGetter;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.StrUtil;

import java.util.Map;

public class ServerConfig implements OptNullBasicTypeFromObjectGetter {

	private ServerConfig() {
	}

	private static ServerConfig ME = new ServerConfig();

	public static ServerConfig me() {
		return ME;
	}
	
	
    private Map config = MapUtil.newHashMap();

    /**
     * 递归取
     * @param key
     * @param <T>
     * @return
     */
    public <T> T deepGet(String key){
        return deepGet(key,config);
    }

    private  <T> T deepGet(String key,Map map){
        String[] keys = StrUtil.splitToArray(key, CharUtil.DOT,2);
        Object object = null;
        if (keys.length > 0){
            object = map.get(keys[0]);
        }
        if (keys.length > 1){
            if (object!=null && object instanceof Map){
                return deepGet(keys[1],(Map) object);
            }
        }
        return (T) object;
    }

    /**
     * 合并
     * @param target
     */
    public void merge(Map target){
        merge(config,target);
    }

    private void merge(Map source,Map target){
        target.forEach((k,v) -> {
            Object sourceValue = source.get(k);
            if (sourceValue != null){
                if (sourceValue instanceof Map && v instanceof Map){
                    merge((Map) sourceValue,(Map) v);
                } else {
                    source.put(k,v);
                }
            } else {
                source.put(k,v);
            }
        });
    }

    @Override
    public Object getObj(Object key, Object defaultValue) {
        Object object = config.get(key);
        return object == null ? defaultValue : object;
    }
}
